package com.lagou.handler;

import com.alibaba.fastjson.JSONObject;
import com.lagou.service.com.lagou.util.SpringContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.util.StringUtils;

public class UserServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
//        if(msg.toString().startsWith("UserService")){
//            UserServiceImpl userService = new UserServiceImpl();
//            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
//            ctx.writeAndFlush(result);
//        }

        //判断参数 是否为 RpcRequest ,符合则调用本地方法，返回数据
        String s = msg.toString();
//        System.out.println(s);
        //将 string 转为 json
        JSONObject jsonObject = JSONObject.parseObject(s);
//        RpcRequest request = JSONObject.toJavaObject(jsonObject, RpcRequest.class);
        if(!StringUtils.isEmpty(jsonObject.getString("className"))){

            //从容器中获取 userServiceImpl
            Object bean = SpringContext.getBean(jsonObject.getString("className"));
            //通过反射调用方法
            Object result = bean.getClass().getMethod(jsonObject.getString("methodName"), String.class).
                    invoke(bean, jsonObject.getString("parameters"));

            ctx.writeAndFlush(result.toString());

        }

    }


}
